<template>
    <div class="weather-container">
        <!-- 搜索输入 -->
        <div class="search-box">
            <input v-model="city" placeholder="输入城市名称" @keyup.enter="handleSearch" class="search-input" />
            <button @click="handleSearch" class="search-button">查询</button>
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="status loading">
            <div class="loader"></div>
            <p>获取天气数据中...</p>
        </div>

        <!-- 错误提示 -->
        <div v-else-if="error" class="status error">
            <span class="error-icon">⚠</span>
            <p>{{ error }}</p>
        </div>

        <!-- 天气展示 -->
        <div v-else-if="weatherData" class="weather-content">
            <!-- 当前天气 -->
            <div class="current-weather">
                <h2 class="location">{{ weatherData.province }} {{ weatherData.city }}</h2>
                <div :class="['weather-main', currentAnimation]">
                    <img :src="currentIcon" class="weather-icon" />
                </div>
                <!-- <div class="temperature">
                    <span class="temp">{{ weatherData.temperature }}</span>
                    <span class="unit">℃</span>
                </div> -->
                <div class="weather-details">
                    <div class="detail-item">
                        <span class="label">今日天气</span>
                        <span class="value">{{ weatherData.weather }}</span>
                    </div>
                    <div class="detail-item">
                        <span class="label">体感温度</span>
                        <span class="value">{{ weatherData.temperature }}℃</span>
                    </div>
                    <div class="detail-item">
                        <span class="label">湿度</span>
                        <span class="value">{{ weatherData.humidity }}%</span>
                    </div>
                    <div class="detail-item">
                        <span class="label">风向</span>
                        <span class="value">{{ weatherData.windDirection }}</span>
                    </div>
                    <div class="detail-item">
                        <span class="label">风力</span>
                        <span class="value">{{ weatherData.windPower }}级</span>
                    </div>
                    <div class="detail-item">
                        <span class="label">数据时间</span>
                        <span class="value">{{ weatherData.reportTime }}</span>
                    </div>
                </div>
            </div>
            <!-- 天气预报 -->
            <div class="weather-forecast">
                <div v-for="(forecast, index) in forecasts" :key="index" class="forecast-item">
                    <div class="forecast-date">{{ formatForecastDate(forecast.date) }}</div>
                    <div :class="['forecast-icon', forecast.animation]">
                        <img :src="forecast.icon" class="icon-small" />
                    </div>
                    <div class="forecast-temp">
                        <span class="high">{{ forecast.dayTemp }}℃</span>
                        <span class="low">{{ forecast.nightTemp }}℃</span>
                    </div>
                    <div class="forecast-weather">{{ forecast.dayWeather }}</div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, watch, nextTick } from 'vue'
import { debounce } from 'lodash-es'
import { spotsInfoStore } from '@/stores/spots'

const spotsStore = spotsInfoStore()

// 高德API配置
const AMAP_KEY = '245c3be9ba6f5f0a54831c3d5b007aa9'
const API_URL = 'https://restapi.amap.com/v3/weather/weatherInfo'


// 天气图标映射
const WEATHER_ICONS = {
    '晴': 'sunny',
    '多云': 'cloudy',
    '阴': 'overcast',
    '雨': 'rain',
    '雪': 'snow',
    '雾': 'fog',
    '沙尘': 'dust',
    '雷阵雨': 'thunder',
    '浮尘': 'dust',
    '霾': 'haze',
}

// 天气动画映射
const WEATHER_ANIMATIONS = {
    '晴': 'sunny',
    '雨': 'rainy',
    '雪': 'snowy',
    '云': 'cloudy'
}

// 响应式数据
const cityname = JSON.parse(localStorage.getItem('cityData'))
const city = ref(cityname)
const weatherData = ref(null)
const forecasts = ref([])
const loading = ref(false)
const error = ref(null)

// 计算属性
const currentIcon = computed(() => {
    return getWeatherIcon(weatherData.value?.weather)
})

const currentAnimation = computed(() => {
    return getWeatherAnimation(weatherData.value?.weather)
})

// 方法定义
const getWeatherIcon = (weather) => {
    const type = Object.keys(WEATHER_ICONS).find(key => weather?.includes(key)) || 'default'
    return `/weather-icons/${WEATHER_ICONS[type]}.png`
}

const getWeatherAnimation = (weather) => {
    const type = Object.keys(WEATHER_ANIMATIONS).find(key => weather?.includes(key)) || ''
    return `weather-${WEATHER_ANIMATIONS[type]}-animation`
}

const formatForecastDate = (dateString) => {
    const date = new Date(dateString)
    return date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' })
}

const handleSearch = debounce(async () => {
    if (!city.value.trim()) return

    try {
        loading.value = true
        error.value = null

        // 发起API请求
        const response = await fetch(
            `${API_URL}?key=${AMAP_KEY}&city=${encodeURIComponent(city.value)}&extensions=all`
        )
        const response2 = await fetch(
            `${API_URL}?key=${AMAP_KEY}&city=${encodeURIComponent(city.value)}&extensions=base`
        )
        if (!response.ok) throw new Error('网络请求失败')

        const data = await response.json()
        const data2 = await response2.json()
        console.log(data2.lives[0]);

        if (data.status !== '1') throw new Error(data.info || '获取数据失败')

        // 处理实时天气数据
        if (data2.lives.length > 0) {
            const liveData = data2.lives[0]
            weatherData.value = {
                province: liveData.province,
                city: liveData.city,
                weather: liveData.weather,
                temperature: liveData.temperature,
                humidity: liveData.humidity,
                windDirection: liveData.winddirection,
                windPower: liveData.windpower,
                reportTime: liveData.reporttime
            }
        }

        // 处理预报数据
        if (data.forecasts.length > 0) {
            forecasts.value = data.forecasts[0].casts.slice(0, 5).map(cast => ({
                date: cast.date,
                dayWeather: cast.dayweather,
                dayTemp: cast.daytemp,
                nightWeather: cast.nightweather,
                nightTemp: cast.nighttemp,
                icon: getWeatherIcon(cast.dayweather),
                animation: getWeatherAnimation(cast.dayweather)
            }))
        }
    } catch (err) {
        error.value = err.message || '获取天气信息失败'
        console.error('天气请求错误:', err)
    } finally {
        loading.value = false
    }
}, 500)



// 生命周期钩子
onMounted(() => {
    handleSearch()
})
watch(() => spotsStore.cityname, (newVal) => {
    city.value = newVal
    handleSearch()
});
onBeforeUnmount(() => {

})
</script>

<style scoped>
/* 基础样式 */
.weather-container {
    max-width: 800px;
    margin: 2rem auto;
    padding: 1.5rem;
    background: #ffffff;
    border-radius: 16px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.weather-content {
    background: #f8f9fa;
    padding: 20px;
    border-radius: 8px;
}

.search-box {
    display: flex;
    gap: 12px;
    margin-bottom: 2rem;
}

.search-input {
    flex: 1;
    padding: 12px 16px;
    border: 2px solid #e0e0e0;
    border-radius: 8px;
    font-size: 16px;
    transition: border-color 0.3s ease;

    &:focus {
        border-color: #4dabf7;
        outline: none;
    }
}

.search-button {
    padding: 12px 24px;
    background: #4dabf7;
    color: white;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    transition: background 0.3s ease;

    &:hover {
        background: #3d8bcf;
    }
}

/* 当前天气样式 */
.current-weather {
    text-align: center;
    padding: 2rem 0;
    border-bottom: 1px solid #eee;
}

.weather-main {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 2rem;
    margin: 1.5rem 0;
}

.weather-icon {
    width: 100px;
    height: 100px;
}

.temperature {
    font-size: 3.5rem;
    font-weight: 300;

    .unit {
        font-size: 1.5rem;
        vertical-align: super;
    }
}

.weather-details {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 1rem;
    margin-top: 1.5rem;

    .detail-item {
        padding: 1rem;
        background: #f8f9fa;
        border-radius: 8px;

        .label {
            display: block;
            color: #666;
            font-size: 0.9em;
            margin-bottom: 0.3rem;
        }

        .value {
            font-weight: 500;
            color: #2c3e50;
        }
    }
}

/* 天气预报样式 */
.weather-forecast {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
    gap: 1rem;
    margin-top: 2rem;
}

.forecast-item {
    padding: 1rem;
    text-align: center;
    background: #f8f9fa;
    border-radius: 8px;
    transition: transform 0.2s ease;

    &:hover {
        transform: translateY(-3px);
    }
}

.forecast-date {
    color: #666;
    font-size: 0.9em;
    margin-bottom: 0.5rem;
}

.icon-small {
    width: 40px;
    height: 40px;
    margin: 5px auto;
}

.forecast-temp {
    margin: 0.5rem 0;

    .high {
        color: #ff6b6b;
        margin-right: 0.5rem;
    }

    .low {
        color: #4dabf7;
    }
}

/* 动画效果 */
@keyframes sunRotate {
    from {
        transform: rotate(0deg);
    }

    to {
        transform: rotate(360deg);
    }
}

.weather-sunny-animation {
    animation: sunRotate 20s linear infinite;
}

@keyframes rainFall {
    from {
        background-position: 0 0;
    }

    to {
        background-position: 20% 100%;
    }
}

.weather-rainy-animation {
    position: relative;

    &::after {
        content: '';
        position: absolute;
        top: -20px;
        left: -20px;
        right: -20px;
        bottom: -20px;
        background: linear-gradient(to bottom,
                rgba(77, 171, 247, 0.1) 0%,
                rgba(77, 171, 247, 0.3) 50%,
                rgba(77, 171, 247, 0.1) 100%);
        animation: rainFall 1s linear infinite;
        pointer-events: none;
    }
}

/* 加载状态 */
.status {
    text-align: center;
    padding: 2rem;

    &.loading {
        color: #4dabf7;
    }

    &.error {
        color: #ff4757;
    }
}

.loader {
    display: inline-block;
    width: 30px;
    height: 30px;
    border: 3px solid #f3f3f3;
    border-radius: 50%;
    border-top-color: #4dabf7;
    animation: spin 1s ease-in-out infinite;
}

@keyframes spin {
    to {
        transform: rotate(360deg);
    }
}
</style>